﻿using fhq.hcmute.core.qrcode;
using fhq.hcmute.core.qrcode.common;
using fhq.hcmute.desktop.image;
using ModernShopping.AppCode;
using ModernShopping.AppCode.WebUtil;
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ModernShopping.User
{
    public partial class UpdateProduct : System.Web.UI.Page
    {
        private const string PRODUCT_CODE = "ProductCode";
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            LoginInfo loginInfo = Session.GetLoginInfo();
            if (loginInfo == null)
            {
                Response.GoToAccessDeniedPage(Request);
            }
            if (!loginInfo.IsUser())
            {
                Response.GoToAccessDeniedPage(Request);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString[PRODUCT_CODE] == null)
                {
                    Response.GoToAccessDeniedPage(Request);
                    return;
                }
                else
                {
                    int ProductCode = int.Parse(Request.QueryString[PRODUCT_CODE]);
                    Product p = DbProduct.GetByCode(ProductCode);
                    ImageDescription.ImageUrl = p.ImageUrl;
                    DisplayProductInfo(p);
                    edtDescription.Content = p.Description;
                    DbStore.InitDropdownList(cboListStore, Session.GetLoginInfo().UserID, ProductCode);
                    if (cboListStore.Items.Count > 0)
                    {
                        int code = int.Parse(cboListStore.SelectedValue);
                        lblAddress.Text = DbStore.GetByID(code).Address;
                    }
                    Session.AddListStore(DbStore.GetList(ProductCode));
                    RefreshGridview();
                }
            }
        }

        private void refreshDropdownList()
        {
            DbStore.RefreshDropdownList(cboListStore, Session.GetLoginInfo().UserID, Session.GetListStore());
        }

        private void RefreshGridview()
        {
            List<Store> listStore = Session.GetListStore();
            gvMyStores.DataSource = listStore;
            gvMyStores.DataBind();
        }

        private void DisplayProductInfo(Product product)
        {
            TxtProductName.Text = product.Name;
            TxtPrice.Text = product.Price.ToString();
            TxtMadeIn.Text = product.MadeIn;
        }

        protected void btnInsertStore_Click(object sender, EventArgs e)
        {
            if (cboListStore.Items.Count > 0)
            {
                int code = int.Parse(cboListStore.SelectedValue);
                Session.AddStoreToList(DbStore.GetByID(code));
                RefreshGridview();
                cboListStore.Items.RemoveAt(cboListStore.SelectedIndex);
            }
            else
            {
                MyPopup.InitPopup("", "Sản phẩm này đã có trong tất cả cửa hàng của công ty.", "red");
                MyPopup.Show();
                return;
            }
        }

        protected void cboListStore_SelectedIndexChanged(object sender, EventArgs e)
        {
            int code = int.Parse(cboListStore.SelectedValue);
            lblAddress.Text = DbStore.GetByID(code).Address;
        }

        protected void gvMyStores_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvMyStores.PageIndex = e.NewPageIndex;
            RefreshGridview();
        }

        protected void lbRemove_Click(object sender, EventArgs e)
        {
            LinkButton lb = (sender as LinkButton);
            int Code = int.Parse(lb.CommandArgument);
            if (Session.RemoveStore(Code))
            {
                RefreshGridview();
                refreshDropdownList();
            }
        }

        private string UpdateImage()
        {
            string srcImage = ImageDescription.ImageUrl;
            if (srcImage.ToLower().Contains("temp"))
            {
                string desImage = Server.MapPath(srcImage.Replace("temp", "products"));
                File.Copy(Server.MapPath(srcImage), desImage, true);
                return srcImage.Replace("temp", "products");
            }
            return ImageDescription.ImageUrl;
        }

        private string CreateQRCode(ProductMapping pm)
        {
            QRCodeWriter qrWriter = new QRCodeWriter(pm.ToString(), ErrorCorrectionLevel.H);
            QRCode qrcode = qrWriter.getQrCode(); ;
            BufferImageUtil.Builder builder = new BufferImageUtil.Builder(qrcode);
            builder.setDotSize(5);
            string ImageURL = string.Format("~/images/QrCode/{0}.png", pm.ProductCode);
            builder.saveToFile(Server.MapPath(ImageURL));
            return ImageURL;
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            Countdown.ShowPopup();
            int ProductCode = int.Parse(Request.QueryString[PRODUCT_CODE]);
            Product product = new Product();
            product.Code = ProductCode;
            product.Name = TxtProductName.Text;
            product.Price = double.Parse(TxtPrice.Text);
            product.Description = edtDescription.Content;
            product.MadeIn = TxtMadeIn.Text;
            product.ImageUrl = UpdateImage();
            product.CompanyCode = Session.GetLoginInfo().UserID;
            if (DbProduct.Update(product))
            {
                ProductMapping productMapping = new ProductMapping();
                productMapping.ProductCode = product.Code;
                productMapping.ProductName = product.Name;
                productMapping.Price = double.Parse(TxtPrice.Text);
                productMapping.MadeIn = product.MadeIn;

                if (DbProductStore.AddOrDelete(ProductCode, Session.GetListStore()) && DbProduct.UpdateQRCode(product.Code, CreateQRCode(productMapping)))
                {
                    Countdown.InitCountdown(3, "Cập nhật đã được lưu lại", "Hệ thống sẽ mở lại trang trong {0} giây nữa", WebUtil.Page.UPDATE_PRODUCT, ProductCode.ToString());
                    Countdown.Start();
                }
            }
            else
            {
                Countdown.HidePopup();
                MyPopup.InitPopup("Cập nhật thất bại", "<Br/>Vui lòng kiểm tra lại thông tin sản phẩm mà bạn nhập vào", "red");
                MyPopup.Show();
            }
        }

        protected void btnOk_Click(object sender, EventArgs e)
        {
            if (FileUpdate.HasFile)
            {
                int ProductCode = int.Parse(Request.QueryString[PRODUCT_CODE]);
                if (!File.Exists(Server.MapPath("~/Images/temp")))
                {
                    Directory.CreateDirectory(Server.MapPath("~/Images/temp"));
                }
                string ImageUrl = "~/Images/temp/{0}{1}";
                ImageUrl = String.Format(ImageUrl, ProductCode, System.IO.Path.GetExtension(FileUpdate.FileName));
                FileUpdate.SaveAs(Server.MapPath(ImageUrl));
                ImageDescription.ImageUrl = ImageUrl;
                ModalPopupExtender.Hide();
            }
        }
    }
}